Skip to content

fix(windows): bypass bmalloc/libpas to fix GC crashes under memory pressure - #28230

Closed
robobun wants to merge 1 commit into
mainfrom
claude/fix-bmalloc-gc-crash-windows-21569
Closed

robobun wants to merge 1 commit into
mainfrom
claude/fix-bmalloc-gc-crash-windows-21569

Conversation

@robobun

@robobun robobun commented Mar 18, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Fixes segmentation fault on Windows during GC sweep (MarkedBlock::isNewlyAllocatedStale) caused by bmalloc's libpas allocator under memory pressure
  • Implements bmalloc's SystemHeap on Windows using mimalloc as the backing allocator (upstream WebKit leaves this unimplemented — all methods crash with RELEASE_BASSERT_NOT_REACHED())
  • Sets Malloc=1 environment variable early in main() to trigger bmalloc's system heap bypass, routing all allocations through our mimalloc-backed SystemHeap instead of libpas

How it works

  1. BmallocSystemHeapOverride.cpp — Provides a working bmalloc::SystemHeap for Windows using mimalloc (mi_malloc, mi_malloc_aligned, mi_realloc, mi_free). At link time, these symbols override bmalloc.lib's unimplemented stubs because object files are resolved before static libraries.

  2. main.zig — Sets Malloc=1 via _putenv before any bmalloc initialization. bmalloc's Environment class reads this and sets shouldBmallocAllocateThroughSystemHeap() = true, causing all allocations to route through SystemHeap.

  3. c-headers-for-zig.h — Adds <stdlib.h> to Windows includes so _putenv is available to Zig code.

Why bmalloc.lib is still linked

WTF.lib references ~230 bmalloc symbols, so bmalloc.lib cannot be removed without rebuilding WebKit prebuilts. This fix works alongside bmalloc.lib by overriding only the SystemHeap symbols. Once oven-sh/WebKit prebuilts are rebuilt without libpas on Windows, bmalloc.lib can be removed entirely.

Fixes #21569

Test plan

  • bun bd compiles successfully on Linux
  • bun run zig:check-windows passes (Windows cross-compilation check)
  • bun run zig:check-all passes (all platform compilation checks)
  • Windows CI: verify no GC crashes under memory pressure
  • Windows CI: verify no duplicate symbol errors at link time

🤖 Generated with Claude Code

…essure

bmalloc's libpas allocator causes segmentation faults on Windows during GC
sweep (MarkedBlock::isNewlyAllocatedStale) under memory pressure. The root
cause is that bmalloc's SystemHeap is unimplemented on Windows — all its
methods call RELEASE_BASSERT_NOT_REACHED().

This fix:
1. Implements SystemHeap on Windows using mimalloc as the backing allocator
   (BmallocSystemHeapOverride.cpp). The object file's symbols override
   bmalloc.lib's unimplemented stubs at link time.
2. Sets Malloc=1 env var early in main() to trigger bmalloc's system heap
   bypass, routing all allocations through our mimalloc-backed SystemHeap
   instead of libpas.

Fixes #21569

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@robobun

robobun commented Mar 18, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 7:12 AM PT - Mar 18th, 2026

❌ Your commit 2b89665f has 6 failures in Build #39972 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 28230

That installs a local version of the PR into your bun-28230 executable, so you can run:

bun-28230 --bun

@github-actions

Copy link
Copy Markdown
Contributor

Found 8 issues this PR may fix:

  1. Crash in bmalloc (pas_assertion_failed) on Windows x64 baseline in standalone executable #26982 - Direct bmalloc/libpas crash on Windows with identical stack trace to what this PR fixes
  2. Segfault after ~24h idle on Windows 11 with sleep/wake cycles #28175 - Windows segfault after extended runtime with memory pressure (3.6M+ page faults)
  3. Segfault after ~24h idle on Windows 11 with sleep/wake cycles (second instance) #28176 - Second report of Windows segfault under memory pressure after 24h runtime
  4. Bun 1.3.11 (integrated in Claude Code) on Windows x64 OOM crash #28174 - Windows OOM crash with AsyncHTTP allocating >2GB for small responses
  5. Bun crashes in Claude Code cause Windows BSOD (KERNEL_SECURITY_CHECK_FAILURE) — full system reboots on Windows 11 x64 #27692 - Windows BSOD caused by Bun memory corruption severe enough to crash kernel
  6. Bun v1.3.10 crashes with segmentation fault on Windows 10 x64 #27414 - Windows segfault after 5 minutes with high memory pressure (10.62GB RSS)
  7. Segfault (null pointer at 0x0) in long-running standalone executable on Windows after sustained memory pressure #26862 - Windows segfault in long-running processes after sustained memory pressure
  8. Bug: Segmentation fault when using ONNX runtime on Windows #28008 - Windows segfault when loading native DLLs, potentially due to allocator conflicts

If this is helpful, consider adding Fixes # to the PR description to auto-close the issue on merge.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

Walkthrough

This PR implements Windows-specific memory allocation improvements by introducing a SystemHeap implementation for bmalloc backed by mimalloc, updating the Windows build configuration to link required WebKit libraries, and setting an environment variable on Windows startup to activate this custom heap behavior.

Changes

Cohort / File(s) Summary
Build Configuration
cmake/targets/BuildBun.cmake
Expanded Windows-specific library linking to include bmalloc, ICU, WTF, JavaScriptCore, and related dependencies for the bun target in both DEBUG and non-DEBUG configurations. Added explanatory comments about bmalloc/libpas interaction.
Memory Allocation Implementation
src/bun.js/bindings/BmallocSystemHeapOverride.cpp
Introduces SystemHeap class in the bmalloc namespace with mimalloc-backed allocation methods (malloc, memalign, realloc, free) for Windows. Adds large-object allocation paths via memalignLarge/freeLarge. Integrates LIBPAS entry points (pas_system_heap_* functions) with fallbacks when LIBPAS is disabled. Includes environment-driven activation and cached per-process SystemHeap getter.
Header Includes
src/c-headers-for-zig.h
Adds <stdlib.h> include directive to Windows-specific header block for _putenv availability.
Runtime Initialization
src/main.zig
Adds Windows-only initialization that invokes _putenv("Malloc=1") before any bmalloc allocations to enable SystemHeap usage on Windows, guarded by Environment.isWindows.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main objective of fixing GC crashes on Windows by bypassing bmalloc/libpas, which aligns with the primary changes in the changeset.
Description check ✅ Passed The PR description comprehensively covers what the PR does and how the fix works, though the test plan includes pending items rather than verification steps already completed.
Linked Issues check ✅ Passed The code changes directly address issue #21569 by implementing a Windows-specific SystemHeap using mimalloc and setting Malloc=1 to route allocations away from the crashing libpas allocator.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the Windows GC crash: SystemHeap implementation, environment variable setup, and header includes for _putenv availability.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

📝 Coding Plan
  • Generate coding plan for human review comments

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/bun.js/bindings/BmallocSystemHeapOverride.cpp`:
- Around line 101-118: The m_sizeMap bookkeeping currently uses operator[]
(m_sizeMap[result] = size) and operator[] lookups (m_sizeMap[base]) which can
silently insert defaults; change the allocation path to insert with a
non-overwriting operation (e.g., emplace/insert) and assert the insert succeeded
(no duplicate key) in the allocation function (where result is stored), and
change SystemHeap::freeLarge to use find() to locate the iterator, assert the
iterator != end (fail if missing), read the size from the iterator, then call
erase(it) and assert erase removed one entry; do not use operator[] anywhere for
m_sizeMap to avoid implicit insertion.
- Around line 23-27: Add the missing source to the BUN_CXX_SOURCES list so the
override is compiled: in BuildBun.cmake, after the comment that documents the
override and before the if(DEBUG) block, append the
BmallocSystemHeapOverride.cpp path to the BUN_CXX_SOURCES variable (i.e., add a
list(APPEND BUN_CXX_SOURCES
${CWD}/src/bun.js/bindings/BmallocSystemHeapOverride.cpp) directive) so the
link-time override in src/bun.js/bindings/BmallocSystemHeapOverride.cpp is built
and the bmalloc stubs are replaced.

In `@src/main.zig`:
- Around line 24-33: Move the Windows allocator switch so it runs as the very
first statement inside main(): check Environment.isWindows and call
_bun.c._putenv("Malloc=1") before any other initialization (in particular before
_bun.crash_handler.init() or any code that may touch WTF/JSC/bmalloc). Ensure
the if (Environment.isWindows) { _ = _bun.c._putenv("Malloc=1"); } block appears
at the top of main() so bmalloc's Environment initializes using SystemHeap
reliably.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: c9801825-2964-4294-b8dd-b0fc8d994bc0

📥 Commits

Reviewing files that changed from the base of the PR and between 76f4f38 and 2b89665.

📒 Files selected for processing (4)
  • cmake/targets/BuildBun.cmake
  • src/bun.js/bindings/BmallocSystemHeapOverride.cpp
  • src/c-headers-for-zig.h
  • src/main.zig

Comment on lines +23 to +27
* Link-time override:
* This object file defines the same symbols as bmalloc.lib's
* SystemHeap.cpp.o. Since object files are processed before static
* libraries, the linker uses these definitions and skips bmalloc.lib's
* unimplemented stubs.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show how Bun collects C++ sources, then confirm the new TU is listed.
rg -n -C1 'absolute_sources\(BUN_CXX_SOURCES' cmake/targets/BuildBun.cmake
rg -n --fixed-strings 'BmallocSystemHeapOverride.cpp' cmake/sources/CxxSources.txt

Repository: oven-sh/bun

Length of output: 390


🏁 Script executed:

# Check if CxxSources.txt exists anywhere or if it's generated
fd -name '*CxxSources*' .

# Look for patterns of how sources might be added to BUN_CXX_SOURCES
rg -n 'BUN_CXX_SOURCES' cmake/targets/BuildBun.cmake

# Check if BmallocSystemHeapOverride.cpp is referenced directly anywhere
rg -n 'BmallocSystemHeapOverride' cmake/

# Look at the structure of cmake/sources/ to understand what files exist there
ls -la cmake/sources/ 2>/dev/null || echo "cmake/sources/ not found"

Repository: oven-sh/bun

Length of output: 732


🏁 Script executed:

# Read around line 1270 where BmallocSystemHeapOverride is mentioned
sed -n '1265,1280p' cmake/targets/BuildBun.cmake

# Check if BmallocSystemHeapOverride.cpp is being appended anywhere
rg -n 'list\(APPEND BUN_CXX_SOURCES' cmake/targets/BuildBun.cmake | head -20

# Check the full Windows-specific section where rescle is appended
sed -n '755,765p' cmake/targets/BuildBun.cmake

Repository: oven-sh/bun

Length of output: 1236


🏁 Script executed:

# Comprehensive search for BmallocSystemHeapOverride being added to any target/sources
rg -i 'BmallocSystemHeapOverride' cmake/

Repository: oven-sh/bun

Length of output: 158


BmallocSystemHeapOverride.cpp is not being compiled—missing list(APPEND BUN_CXX_SOURCES ...) directive.

The override file is documented in the comment at cmake/targets/BuildBun.cmake:1270, but it is never added to the build. Add this line after the comment and before the if(DEBUG) block:

list(APPEND BUN_CXX_SOURCES ${CWD}/src/bun.js/bindings/BmallocSystemHeapOverride.cpp)

Without this, the entire override mechanism is non-functional and Windows will continue to use the problematic bmalloc stubs.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/bun.js/bindings/BmallocSystemHeapOverride.cpp` around lines 23 - 27, Add
the missing source to the BUN_CXX_SOURCES list so the override is compiled: in
BuildBun.cmake, after the comment that documents the override and before the
if(DEBUG) block, append the BmallocSystemHeapOverride.cpp path to the
BUN_CXX_SOURCES variable (i.e., add a list(APPEND BUN_CXX_SOURCES
${CWD}/src/bun.js/bindings/BmallocSystemHeapOverride.cpp) directive) so the
link-time override in src/bun.js/bindings/BmallocSystemHeapOverride.cpp is built
and the bmalloc stubs are replaced.

Comment on lines +101 to +118
{
LockHolder locker(mutex());
m_sizeMap[result] = size;
}
return result;
}

void SystemHeap::freeLarge(void* base)
{
if (!base)
return;

size_t size;
{
LockHolder locker(mutex());
size = m_sizeMap[base];
size_t numErased = m_sizeMap.erase(base);
RELEASE_BASSERT(numErased == 1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Use non-inserting map operations for m_sizeMap bookkeeping.

Line 116 inserts a default entry when base is missing, so numErased == 1 still passes and this can fall through to vmDeallocate(base, 0) instead of tripping the invariant. Line 103 has the dual problem: it silently overwrites duplicate keys. This allocator metadata should use an asserting insert on allocation and a find/erase-by-iterator path on free.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/bun.js/bindings/BmallocSystemHeapOverride.cpp` around lines 101 - 118,
The m_sizeMap bookkeeping currently uses operator[] (m_sizeMap[result] = size)
and operator[] lookups (m_sizeMap[base]) which can silently insert defaults;
change the allocation path to insert with a non-overwriting operation (e.g.,
emplace/insert) and assert the insert succeeded (no duplicate key) in the
allocation function (where result is stored), and change SystemHeap::freeLarge
to use find() to locate the iterator, assert the iterator != end (fail if
missing), read the size from the iterator, then call erase(it) and assert erase
removed one entry; do not use operator[] anywhere for m_sizeMap to avoid
implicit insertion.

Comment thread src/main.zig
Comment on lines +24 to +33
// Force bmalloc to use SystemHeap (mimalloc) instead of libpas on Windows.
// bmalloc's libpas allocator causes GC crashes under memory pressure on
// Windows. Setting "Malloc" causes bmalloc::Environment to route all
// allocations through SystemHeap, which we implement using mimalloc
// (see BmallocSystemHeapOverride.cpp). Must be set before any bmalloc
// allocation triggers Environment initialization.
// See: https://github.com/oven-sh/bun/issues/21569
if (Environment.isWindows) {
_ = _bun.c._putenv("Malloc=1");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Make the allocator switch the first statement in main().

Line 22 still runs before this block, so the workaround currently depends on _bun.crash_handler.init() never touching WTF/JSC allocation. Moving _putenv("Malloc=1") to the top removes that hidden ordering requirement and makes the fix robust against future refactors.

Proposed reorder
 pub fn main() void {
-    _bun.crash_handler.init();
-
     // Force bmalloc to use SystemHeap (mimalloc) instead of libpas on Windows.
     // bmalloc's libpas allocator causes GC crashes under memory pressure on
     // Windows. Setting "Malloc" causes bmalloc::Environment to route all
     // allocations through SystemHeap, which we implement using mimalloc
     // (see BmallocSystemHeapOverride.cpp). Must be set before any bmalloc
     // allocation triggers Environment initialization.
     // See: https://github.com/oven-sh/bun/issues/21569
     if (Environment.isWindows) {
         _ = _bun.c._putenv("Malloc=1");
     }
+
+    _bun.crash_handler.init();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main.zig` around lines 24 - 33, Move the Windows allocator switch so it
runs as the very first statement inside main(): check Environment.isWindows and
call _bun.c._putenv("Malloc=1") before any other initialization (in particular
before _bun.crash_handler.init() or any code that may touch WTF/JSC/bmalloc).
Ensure the if (Environment.isWindows) { _ = _bun.c._putenv("Malloc=1"); } block
appears at the top of main() so bmalloc's Environment initializes using
SystemHeap reliably.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR adds a new memory allocator override for Windows (287-line BmallocSystemHeapOverride.cpp) that relies on link-time symbol resolution and bmalloc internals — a human should verify the SystemHeap implementation correctness and the link-time override strategy before merging.

Extended reasoning...

Overview

This PR fixes Windows GC crashes under memory pressure by bypassing bmalloc/libpas. It adds a new BmallocSystemHeapOverride.cpp (287 lines) implementing bmalloc::SystemHeap backed by mimalloc, sets Malloc=1 env var early in main.zig to trigger bmalloc's system heap bypass, adds <stdlib.h> to c-headers-for-zig.h for _putenv, and adds explanatory comments to BuildBun.cmake.

Security risks

Memory allocator overrides are inherently security-sensitive. An incorrect implementation could lead to memory corruption, use-after-free, or other exploitable conditions. The memalignLarge/freeLarge functions use a m_sizeMap that must be correctly maintained under concurrent access — while a lock is used, the correctness of the locking strategy relative to bmalloc's threading model needs human verification. Setting environment variables (Malloc=1) at startup could theoretically be observable by other code.

Level of scrutiny

This warrants careful human review. It touches the allocator subsystem, which is one of the most correctness-critical parts of a runtime. The link-time symbol override approach (object files taking precedence over static library symbols) is a well-known linker behavior but relies on MSVC/link.exe specifics. The new C++ file must exactly match bmalloc's SystemHeap interface — any mismatch in method signatures, calling conventions, or semantics could cause subtle runtime failures. The test plan also has unchecked Windows CI items.

Other factors

  • The PR is labeled claude, indicating it was auto-generated by Claude Code
  • No human reviewers have weighed in yet
  • The approach of overriding SystemHeap while keeping bmalloc.lib linked is a pragmatic workaround, but the long-term plan (rebuilding WebKit prebuilts) should be tracked
  • The BmallocSystemHeapOverride.cpp will be automatically picked up by the build via the src/bun.js/bindings/*.cpp glob in Sources.json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Segmentation Fault in Bun v1.2.18 on Windows x86_64 during RunCommand (JSC::MarkedBlock::isNewlyAllocatedStale)

1 participant